import * as THREE from 'three'
import { gui } from '../gui'
import { stats } from '../stats'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { RectAreaLightUniformsLib } from 'three/examples/jsm/lights/RectAreaLightUniformsLib'
import { RectAreaLightHelper } from 'three/examples/jsm/helpers/RectAreaLightHelper'

function createCourse12 (dom: HTMLElement) {
  const scene = new THREE.Scene()
  const camera = new THREE.PerspectiveCamera(75, dom.offsetWidth / dom.offsetHeight, 0.1, 1000)

  const render = new THREE.WebGLRenderer()
  render.setClearColor(new THREE.Color(0x000000))
  render.setSize(dom.offsetWidth, dom.offsetHeight)
  render.shadowMap.enabled = true

  dom.appendChild(render.domElement)

  // show axes in the screen
  // const axes = new THREE.AxesHelper(50)
  // scene.add(axes);

  const planeGeometry = new THREE.PlaneGeometry(100, 100)
  const planeMaterial = new THREE.MeshLambertMaterial({ color: 0xAAAAAA })
  const plane = new THREE.Mesh(planeGeometry, planeMaterial)

  plane.rotation.x = -0.5 * Math.PI
  plane.position.set(15, 0, 0)
  plane.receiveShadow = true

  scene.add(plane)

  camera.position.x = 0
  camera.position.y = 6
  camera.position.z = -10
  camera.lookAt(scene.position)
  scene.add(camera)

  const directionalLight = new THREE.DirectionalLight(0xffffff, 4)
  directionalLight.castShadow = true
  directionalLight.shadow.mapSize.width = 2048
  directionalLight.shadow.mapSize.height = 2048
  directionalLight.position.set(20, 20, 20)
  // scene.add(directionalLight);

  const controls = new OrbitControls(camera, render.domElement)
  controls.update()

  RectAreaLightUniformsLib.init()
  const rectLight = new THREE.RectAreaLight(0xff0000, 5, 4, 10)
  rectLight.position.set(0, 0, 0)
  scene.add(rectLight)

  const geoFloor = new THREE.BoxGeometry(2000, 0.1, 2000)
  const matStdFloor = new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.2 })
  const mshStdFloor = new THREE.Mesh(geoFloor, matStdFloor)
  scene.add(mshStdFloor)

  const rectLightHelper = new RectAreaLightHelper(rectLight)
  scene.add(rectLightHelper)

  const ctrlObj = {
    areaColor: 0xff0000,
    areaIntensity: 1
  }
  const ctrl = gui
  const areaLightFolder = ctrl.addFolder('AreaLight')
  areaLightFolder.addColor(ctrlObj, 'areaColor').onChange(function (e: number) {
    rectLight.color = new THREE.Color(e)
  })
  areaLightFolder.add(ctrlObj, 'areaIntensity', 0, 10).onChange(function (e: number) {
    rectLight.intensity = e
  })

  render.setAnimationLoop(anmation)

  function anmation () {
    stats.update()
    render.render(scene, camera)
  }

  return { camera, scene, render }
}

export {
  createCourse12
}
